/*
 * Copyright 2007 (C) Filippos Slavik (filippos@slavik.gr)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 */
package gr.slavik.android.sip.provider;

import java.util.HashMap;
import java.util.Map;

import gr.slavik.android.provider.SIPSettings;
import gr.slavik.android.sip.activity.SIPAccountsList;
import android.content.ContentProvider;
import android.content.ContentProviderDatabaseHelper;
import android.content.ContentURIParser;
import android.content.ContentValues;
import android.content.QueryBuilder;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.ContentURI;
import android.text.TextUtils;
import android.util.Log;

/**
 * @author <a mailto:filippos@slavik.gr>Filippos Slavik</a>
 * 
 */
public class SIPSettingsProvider extends ContentProvider {
	
	/**
	 * A <code>TAG</code> constant to be used for logging.
	 */
	private static final String TAG = "SIPSettings Provider"; 

	private SQLiteDatabase mDB;

    private static final String DATABASE_NAME = "sip_settings.db";
    
    private static final int DATABASE_VERSION = 2;
    
    private static final int ACCOUNTS = 1;
    
    private static final int ACCOUNT_ID = 2;
    

    private static final ContentURIParser URL_MATCHER;
    
    private static Map<String, String> NOTES_LIST_PROJECTION_MAP;
    
    private static class DatabaseHelper extends ContentProviderDatabaseHelper {

		/**
		 * @see android.content.ContentProviderDatabaseHelper#onCreate(android.database.sqlite.SQLiteDatabase)
		 */
		@Override
		public void onCreate(SQLiteDatabase db) {
			db.execSQL("CREATE TABLE accounts " +
					"( _id INTEGER PRIMARY KEY AUTOINCREMENT, " +
					SIPSettings.Accounts.PROFILE_NAME+ " VARCHAR(64), " +
					SIPSettings.Accounts.DISPLAY_NAME+ " VARCHAR(128)," +
					SIPSettings.Accounts.CREATED_DATE+" INTEGER," +
					SIPSettings.Accounts.MODIFIED_DATE+" INTEGER);");
		}

		/**
		 * @see android.content.ContentProviderDatabaseHelper#onUpgrade(android.database.sqlite.SQLiteDatabase,
		 *      int, int)
		 */
		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data.");
            db.execSQL("DROP TABLE IF EXISTS accounts");
            onCreate(db);
		}
    	
    }
	static {
		URL_MATCHER = new ContentURIParser(ContentURIParser.NO_MATCH);
		URL_MATCHER.addURI(SIPSettings.CONTENT_URI_AUTHORITY_PART, SIPSettings.Accounts.DATA_PATH, ACCOUNTS);
		URL_MATCHER.addURI(SIPSettings.CONTENT_URI_AUTHORITY_PART, SIPSettings.Accounts.DATA_PATH.concat("/#"), ACCOUNT_ID);
		
		NOTES_LIST_PROJECTION_MAP = new HashMap<String, String>();
        NOTES_LIST_PROJECTION_MAP.put(SIPSettings.Accounts._ID, "_id");
        NOTES_LIST_PROJECTION_MAP.put(SIPSettings.Accounts.PROFILE_NAME, SIPSettings.Accounts.PROFILE_NAME);
        NOTES_LIST_PROJECTION_MAP.put(SIPSettings.Accounts.DISPLAY_NAME, SIPSettings.Accounts.DISPLAY_NAME);
        NOTES_LIST_PROJECTION_MAP.put(SIPSettings.Accounts.CREATED_DATE, SIPSettings.Accounts.CREATED_DATE);
        NOTES_LIST_PROJECTION_MAP.put(SIPSettings.Accounts.MODIFIED_DATE, SIPSettings.Accounts.MODIFIED_DATE);

	}
	/**
	 * @see android.content.ContentProvider#delete(android.net.ContentURI,
	 *      java.lang.String, java.lang.String[])
	 */
	@Override
	public int delete(ContentURI uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	/**
	 * @see android.content.ContentProvider#getType(android.net.ContentURI)
	 */
	@Override
	public String getType(ContentURI uri) {
		switch(URL_MATCHER.match(uri)) {
		case ACCOUNTS:
			return "vnd.slavik.gr.cursor.dir/vnd.slavik.gr.sipaccount";
		case ACCOUNT_ID:
			return "vnd.slavik.gr.cursor.item/vnd.slavik.gr.sipaccount";
		default:
			throw new IllegalArgumentException("Unknown Content URI "+uri);
		}
	}

	/**
	 * @see android.content.ContentProvider#insert(android.net.ContentURI,
	 *      android.content.ContentValues)
	 */
	@Override
	public ContentURI insert(ContentURI uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * @see android.content.ContentProvider#onCreate()
	 */
	@Override
	public boolean onCreate() {
		DatabaseHelper dbHelper = new DatabaseHelper();
        mDB = dbHelper.openDatabase(getContext(), DATABASE_NAME, null, DATABASE_VERSION);
        Log.d(TAG, mDB.toString());
        Log.d(TAG,SIPSettings.Accounts.CONTENT_URI.toString());
        return (mDB == null) ? false : true;
	}

	/**
	 * @see android.content.ContentProvider#query(android.net.ContentURI,
	 *      java.lang.String[], java.lang.String, java.lang.String[],
	 *      java.lang.String, java.lang.String, java.lang.String)
	 */
	@Override
	public Cursor query(ContentURI uri, String[] projection, String selection,
			String[] selectionArgs, String groupBy, String having,
			String sortOrder) {
		 QueryBuilder qb = new QueryBuilder();

	        switch (URL_MATCHER.match(uri)) {
	        case ACCOUNTS:
	            qb.setTables("accounts");
	            qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP);
	            break;

	        case ACCOUNT_ID:
	            qb.setTables("accounts");
	            qb.appendWhere("_id=" + uri.getPathSegment(1));
	            break;

	        default:
	            throw new IllegalArgumentException("Unknown Content URI " + uri);
	        }

	        // If no sort order is specified use the default
	        String orderBy;
	        if (TextUtils.isEmpty(sortOrder)) {
	            orderBy = SIPSettings.Accounts.DEFAULT_SORT_ORDER;
	        } else {
	            orderBy = sortOrder;
	        }

	        Cursor c = qb.query(mDB, projection, selection, selectionArgs, groupBy,
	                having, orderBy);
	        c.setNotificationUri(getContext().getContentResolver(), uri);
	        return c;
	}


	/**
	 * @see android.content.ContentProvider#update(android.net.ContentURI,
	 *      android.content.ContentValues, java.lang.String, java.lang.String[])
	 */
	@Override
	public int update(ContentURI uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	

}
